package struts.util;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


public class XmlReader {
	//解析xml文件
	@SuppressWarnings("rawtypes")
	public static Map<String, XmlBean> parse(String filePath){
		Map<String, XmlBean> map = new HashMap<String, XmlBean>();
		SAXReader sax = new SAXReader();
		try {
			Document document = sax.read(new File(filePath));
			Element root = document.getRootElement();
			
			Element actionMapping = root.element("action-mapping");
			for(Iterator it = actionMapping.elementIterator(); it.hasNext();){
				XmlBean bean = new XmlBean();
				Element action = (Element) it.next();
				String actionName = action.attributeValue("name");
				bean.setName(actionName);
				Element formbeans = root.element("formbeans");
				for(Iterator iterator = formbeans.elementIterator(); iterator.hasNext();){
					Element formBean = (Element) iterator.next();
					String beanName = formBean.attributeValue("name");
					if(actionName.equals(beanName)){
						String beanClass = formBean.attributeValue("class");
						bean.setBeanClass(beanClass);
						break;
					}
				}
				
				String actionType = action.attributeValue("type");
				bean.setActionType(actionType);
				String requestPath = action.attributeValue("path");
				bean.setRequestPath(requestPath);
				Map<String, String> forwardMap = new HashMap<String, String>();
				for(Iterator iter = action.elementIterator();iter.hasNext();){
					Element forward = (Element) iter.next();
					String forwardName = forward.attributeValue("name");
					String viewPath = forward.attributeValue("value");
					forwardMap.put(forwardName, viewPath);
				}
				bean.setForward(forwardMap);
				map.put(requestPath, bean);
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return map;
	} 
}
